package com.icesoft.base.manager.controller.manager;

import com.icesoft.base.manager.config.UrlConstant;
import com.icesoft.base.manager.entity.security.SysMenu;
import com.icesoft.base.manager.entity.security.SysRole;
import com.icesoft.base.manager.helper.DataScopeEnum;
import com.icesoft.base.manager.helper.PageParam;
import com.icesoft.base.manager.helper.PageResp;
import com.icesoft.base.manager.helper.QueryBuilderUtils;
import com.icesoft.base.manager.service.security.AuthUserService;
import com.icesoft.base.manager.service.security.SysMenuService;
import com.icesoft.base.manager.service.security.SysRoleService;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.common.helper.TreeBean;
import com.icesoft.core.dao.criteria.Page;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.web.helper.RequestHold;
import lombok.AllArgsConstructor;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色管理相关接口
 */
@RestController
@RequestMapping("manager/role/")
@AllArgsConstructor
public class SysRoleController {
    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;
    private final AuthUserService authUserService;

    /**
     * 根据id查询角色的接口
     */
    @GetMapping(value = UrlConstant.LOAD)
    public Resp load(int id) {
        return Resp.success(sysRoleService.load(id));
    }

    /**
     * 角色数据范围分类列表
     */
    @GetMapping(value = "dataScope")
    public Resp dataScope() {
        return Resp.success(DataScopeEnum.toMap());
    }

    /**
     * 修改角色的接口
     */
    @PostMapping(value = UrlConstant.UPDATE)
    public Resp update(SysRole queryParam) {
        SysRole sysRole = sysRoleService.findByName(queryParam.getName());
        if (sysRole != null && !sysRole.getId().equals(queryParam.getId())) {
            return Resp.error("角色名已存在");
        }
        sysRoleService.updateNotNullProperties(queryParam);
        return Resp.success();
    }

    /**
     * 修改角色菜单
     */
    @PostMapping(value = "updateRoleMenu")
    public Resp updateRoleMenu(HttpServletRequest request, @RequestParam int roleId) {
        int[] menuIds = RequestHold.getIntArray(request, "menuIds", ",");
        sysRoleService.updateRoleMenu(roleId, menuIds);
        return Resp.success();
    }

    /**
     * 修改角色接口权限
     */
    @PostMapping(value = "updateRoleAuthority")
    public Resp updateRoleAuthority(HttpServletRequest request, @RequestParam int roleId) {
        int[] authorityIds = RequestHold.getIntArray(request, "authorityIds", ",");
        sysRoleService.updateRoleAuthority(roleId, authorityIds);
        authUserService.reloadAuthority(roleId);
        return Resp.success();
    }

    /**
     * 修改角色数据范围
     */
    @PostMapping(value = "updateRoleOrg")
    public Resp updateRoleOrg(HttpServletRequest request, @RequestParam int roleId) {
        int[] orgIds = RequestHold.getIntArray(request, "orgIds", ",");
        sysRoleService.updateRoleOrg(roleId, orgIds);
        return Resp.success();
    }

    /**
     * 查询角色列表接口
     */
    @GetMapping(UrlConstant.QUERY)
    public PageResp query(HttpServletRequest request, SysRole queryParam, String search, PageParam pageParam) {
        QueryBuilder queryBuilder = QueryBuilder.get();
        QueryBuilderUtils.addRequestParam(queryBuilder, request, queryParam);
        QueryBuilderUtils.addSearchParam(queryBuilder, search, new String[]{"name"});
        Page<SysRole> page = sysRoleService.page(queryBuilder, pageParam);
        return new PageResp<>(page);
    }

    /**
     * 添加角色的接口
     */
    @PostMapping(value = UrlConstant.CREATE)
    public Resp<Integer> create(@Valid SysRole sysRole) {
        sysRoleService.create(sysRole);
        return Resp.success(sysRole.getId());
    }

    /**
     * 删除角色的接口
     */
    @PostMapping(value = UrlConstant.DELETE)
    public Resp<?> delete(int[] ids) {
        sysRoleService.delete(ids);
        return Resp.success();
    }

    /**
     * 查询角色菜单树的接口
     */
    @GetMapping(value = "/menuTree")
    public Resp<?> menuTree(@RequestParam(defaultValue = "0", required = false) int roleId) {
        List<SysMenu> sysMenus = sysMenuService.findAll();
        List<TreeBean> trees = new ArrayList<>(sysMenus.size());
        List<SysMenu> roleSysMenus = roleId > 0 ? sysMenuService.findByRoleId(roleId) : null;
        sysMenus.forEach(menu -> {
            TreeBean treeBean = new TreeBean();
            treeBean.setId(menu.getId() + "");
            treeBean.setName(menu.getTitle());
            treeBean.setpId(menu.getPid() + "");
            treeBean.setOpen(true);
            if (roleSysMenus != null && roleSysMenus.contains(menu)) {
                treeBean.setChecked(true);
            }
            trees.add(treeBean);
        });
        return Resp.success(trees);
    }
}
